package com.vitas.coin.util;

import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class Http {

    static OkHttpClient mClient;

    static class HttpLogger implements HttpLoggingInterceptor.Logger {
        @Override
        public void log(String message) {
            Log.e("okok", message);
        }
    }

    public static OkHttpClient getClient() {
        if (mClient == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .connectTimeout(35000, TimeUnit.MILLISECONDS)
                    .readTimeout(35000, TimeUnit.MILLISECONDS)
                    .writeTimeout(35000, TimeUnit.MILLISECONDS)
                    .hostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String s, SSLSession sslSession) {
                            return true;
                        }
                    });
            HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLogger()).setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(logInterceptor);
            mClient = builder.build();
        }
        return mClient;
    }

    public static String get(String url, @NonNull Map<String, String> param,
                             Map<String, String> header) throws Exception {
        Request request = getReqBuilder(url, param, header).get().build();
        Response response = getClient().newCall(request).execute();
        String str = response.body().string();
        return str;
    }

    private static Request.Builder getReqBuilder(String url, @NonNull Map<String, String> param, Map<String, String> header) {
        StringBuffer sb = new StringBuffer();
        for (String key : param.keySet()) {
            String v = param.get(key);
            if (v == null) {
                continue;
            }
            sb.append("&")
                    .append(key)
                    .append("=")
                    .append(URLEncoder.encode(v));

        }
        String s = sb.toString();
        if (!TextUtils.isEmpty(s)) {
            s = s.substring(1);
            url += "?" + s;
        }
        Request.Builder builder = new Request.Builder().url(url);
        if (header != null && !header.isEmpty()) {
            for (String key : header.keySet()) {
                builder.header(key, header.get(key));
            }
        }
        return builder;
    }
}
